<template>
  <view class="private-chat-container" :style="chatContainerStyle">

    <!-- 消息列表 -->
    <scroll-view
      class="message-list"
      :style="messageListStyle"
      scroll-y
      :scroll-top="scrollTop"
      @scrolltoupper="loadMoreMessages"
      :enhanced="true"
      :bounces="true"
      :scroll-with-animation="true"
    >
      <view
        v-for="message in messages"
        :key="message.id"
        class="message-item"
        :class="{ 'own-message': message.sender_id.toString() === currentUser?.id?.toString() }"
      >
        <!-- 对方消息 -->
        <view v-if="message.sender_id.toString() !== currentUser?.id?.toString()" class="message-wrapper left-message">
          <view class="avatar-container clickable-avatar" @click="showContactInfo" @longpress="showAvatarTip">
            <image
              :src="getOtherAvatarUrl(message)"
              class="user-avatar"
              :class="{ 'placeholder-avatar': !hasOtherAvatar(message) }"
              mode="aspectFill"
            />
            <view v-if="!hasOtherAvatar(message)" class="avatar-placeholder-text">
              <text>{{ getOtherAvatarInitial(message) }}</text>
            </view>
            <!-- 联系方式提示图标 -->
            <view class="contact-hint">
              <text class="hint-icon">📞</text>
            </view>
          </view>
          <view class="message-content">
            <view class="message-bubble left-bubble">
              <text class="message-text">{{ message.content }}</text>
            </view>
            <view class="message-time">
              {{ formatTime(message.created_at) }}
            </view>
          </view>
        </view>

        <!-- 自己的消息 -->
        <view v-else class="message-wrapper right-message">
          <view class="message-content">
            <view class="message-bubble right-bubble">
              <text class="message-text">{{ message.content }}</text>
            </view>
            <view class="message-time">
              {{ formatTime(message.created_at) }}
            </view>
          </view>
          <view class="avatar-container">
            <image
              v-if="currentUser?.avatar_url"
              :src="currentUser.avatar_url"
              class="user-avatar"
            />
            <view v-else class="avatar-placeholder">
              <text>{{ currentUser?.nickname?.charAt(0) || '我' }}</text>
            </view>
          </view>
        </view>
      </view>

      <!-- 加载更多提示 -->
      <view v-if="isLoadingMore" class="loading-more">
        <text>加载中...</text>
      </view>

      <!-- 空状态 -->
      <view v-if="!isLoading && messages.length === 0" class="empty-state">
        <text class="empty-text">开始你们的对话吧</text>
      </view>
    </scroll-view>

    <!-- 底部输入区域 -->
    <view class="input-section" :style="{ bottom: `${keyboardHeight}px` }">
      <view class="input-container">
        <view class="contact-btn-left" @click="showContactInfo">
          <text class="contact-icon">📞</text>
        </view>
        <input
          v-model="inputMessage"
          class="message-input"
          placeholder="输入消息..."
          @confirm="sendMessage"
          confirm-type="send"
          :adjust-position="false"
        />
        <button
          class="send-btn"
          @click="sendMessage"
          :disabled="!inputMessage.trim() || isSending"
        >
          {{ isSending ? '发送中' : '发送' }}
        </button>
      </view>
    </view>

    <!-- 联系方式查看弹窗 -->
    <view v-if="showContactModal" class="modal-overlay" @click="closeContactModal">
      <view class="contact-modal" @click.stop>
        <view class="modal-header">
          <text class="modal-title">联系方式</text>
          <text class="modal-close" @click="closeContactModal">×</text>
        </view>
        <view class="modal-content">
          <view v-if="contactInfo.loading" class="loading-state">
            <text>正在获取联系方式...</text>
          </view>
          <view v-else-if="contactInfo.error" class="error-state">
            <text class="error-text">{{ contactInfo.error }}</text>
            <button class="retry-btn" @click="getContactInfo">重试</button>
          </view>
        <view v-else-if="contactInfo.data" class="contact-info">
          <view class="user-info">
            <view class="contact-avatar-wrapper">
              <image
                :src="otherUserInfo?.avatar_url || defaultAvatarDataUrl"
                class="contact-avatar"
                :class="{ 'placeholder-avatar': !otherUserInfo?.avatar_url }"
                mode="aspectFill"
              />
              <view v-if="!otherUserInfo?.avatar_url" class="contact-avatar-overlay">
                <text>{{ otherUserInfo?.nickname?.charAt(0) || '用' }}</text>
              </view>
            </view>
              <text class="contact-name">{{ otherUserInfo?.nickname || '用户' }}</text>
            </view>
            <view class="contact-details">
              <view v-if="contactInfo.data.phone_number" class="contact-item">
                <text class="contact-label">手机号：</text>
                <text class="contact-value">{{ contactInfo.data.phone_number }}</text>
                <view class="contact-actions">
                  <button class="action-btn copy-btn" @click="copyText(contactInfo.data.phone_number)">复制</button>
                  <button class="action-btn call-btn" @click="makePhoneCall(contactInfo.data.phone_number)">拨打</button>
                </view>
              </view>
              <view v-if="contactInfo.data.wechat_id" class="contact-item">
                <text class="contact-label">微信号：</text>
                <text class="contact-value">{{ contactInfo.data.wechat_id }}</text>
                <view class="contact-actions">
                  <button class="action-btn copy-btn" @click="copyText(contactInfo.data.wechat_id)">复制</button>
                </view>
              </view>

              <!-- 如果没有任何联系方式的提示 -->
              <view v-if="!contactInfo.data.phone_number && !contactInfo.data.wechat_id" class="no-contact-info">
                <text class="no-contact-text">该用户暂未设置联系方式</text>
              </view>

              <view v-if="!contactInfo.data.is_free" class="fee-info">
                <text class="fee-text">本次查看费用：¥{{ contactInfo.data.cost }}</text>
              </view>
              <view v-if="contactInfo.data.remaining_free_views !== undefined" class="remaining-info">
                <text class="remaining-text">本月剩余免费次数：{{ contactInfo.data.remaining_free_views }}</text>
              </view>
            </view>
          </view>
          <view v-else class="permission-check">
            <view class="check-info">
              <text class="check-title">查看联系方式</text>
              <text v-if="contactPermission.is_free" class="check-message">{{ contactPermission.message }}</text>
              <text v-else class="check-fee">{{ contactPermission.message }}</text>
            </view>
            <view class="check-actions">
              <button class="cancel-btn" @click="closeContactModal">取消</button>
              <button class="confirm-btn" @click="confirmViewContact">
                {{ getViewButtonText() }}
              </button>
            </view>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, reactive, computed, nextTick, onMounted, onUnmounted } from 'vue'
import { onLoad, onUnload } from '@dcloudio/uni-app'
import { chatAPI, contactViewAPI, userAPI, utils } from '@/utils/api.js'
import CreditChecker from '@/utils/creditChecker.js'

const FREE_USAGE_STORAGE_KEY = 'chat_free_usage'

const getTodayKey = () => new Date().toISOString().slice(0, 10)

const incrementFreeUsageCounter = (count = 1) => {
  const today = getTodayKey()
  const record = uni.getStorageSync(FREE_USAGE_STORAGE_KEY)
  let used = 0
  if (record && record.date === today) {
    used = Number(record.used) || 0
  }
  used += count
  uni.setStorageSync(FREE_USAGE_STORAGE_KEY, { date: today, used })
}

const getChatQuotaDataFromError = (error) => {
  return (
    error?.responseData?.data?.chat_quota ||
    error?.data?.chat_quota ||
    null
  )
}

const showFreeChatQuotaModal = (quotaData = {}) => {
  const remaining = Math.max(0, quotaData.remaining ?? 0)
  const dailyLimit = quotaData.dailyLimit ?? 0
  const required = quotaData.required ?? 1
  let content = ''

  if (remaining <= 0) {
    content = `今日免费消息次数已用完（每日上限 ${dailyLimit} 条）。`
  } else {
    content = `今日剩余 ${remaining} 条免费消息，本次操作需要 ${required} 条。`
  }

  content += '\n\n当前为免费模式，套餐额度不会生效，请等待次日自动恢复后再发送。'

  uni.showModal({
    title: '免费消息次数不足',
    content,
    showCancel: false,
    confirmText: '知道了'
  })
}

// 响应式数据
const messages = ref([])
const inputMessage = ref('')
const isLoading = ref(false)
const isLoadingMore = ref(false)
const isSending = ref(false)
const scrollTop = ref(0)
const hasMore = ref(true)
const keyboardHeight = ref(0)
const windowHeight = ref(0)
const pageHeight = ref(0)

// 页面参数
const otherUserId = ref(null)
const otherUserNickname = ref('用户')
const otherUserInfo = ref(null)
const defaultAvatarDataUrl = 'data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" width="80" height="80" viewBox="0 0 80 80"><rect width="80" height="80" rx="8" fill="%23e5e5e5"/><path d="M40 12c8.284 0 15 6.716 15 15s-6.716 15-15 15-15-6.716-15-15 6.716-15 15-15zm0 34c11.598 0 21 6.85 21 15.3V66H19v-4.7C19 52.85 28.402 46 40 46z" fill="%23999"/></svg>'

// 联系方式查看相关
const showContactModal = ref(false)
const contactPermission = ref({})
const contactInfo = reactive({
  loading: false,
  error: null,
  data: null
})

// 分页参数
const pagination = ref({
  page: 1,
  pageSize: 50
})

// 轮询相关
let pollingTimer = null
const pollingInterval = 3000 // 3秒轮询一次

// 计算属性
const currentUser = computed(() => {
  const user = utils.getCurrentUser()
  console.log('📱 Current user from storage:', user)
  console.log('📱 Current user ID type:', typeof user?.id, 'value:', user?.id)
  return user
})

// 计算页面容器的动态样式
const chatContainerStyle = computed(() => {
  return {
    height: pageHeight.value > 0 ? `${pageHeight.value}px` : '100vh'
  }
})

// 计算消息列表的动态样式
const messageListStyle = computed(() => {
  const inputSectionHeight = 140 // 输入区域的高度 rpx
  const keyboardHeightRpx = keyboardHeight.value * 2 // px转rpx
  const bottomPadding = inputSectionHeight + keyboardHeightRpx
  return {
    paddingBottom: `${bottomPadding}rpx`,
    transition: 'padding-bottom 0.3s ease'
  }
})

// 生命周期
onLoad((options) => {
  const { userId, nickname } = options
  if (userId) {
    otherUserId.value = parseInt(userId)
    otherUserNickname.value = decodeURIComponent(nickname || '用户')
    loadOtherUserInfo()
    loadMessages()
    startPolling()
  } else {
    uni.showToast({
      title: '参数错误',
      icon: 'none'
    })
    setTimeout(() => {
      uni.navigateBack()
    }, 1500)
  }
})

onMounted(() => {
  // 获取系统信息并设置页面高度
  uni.getSystemInfo({
    success: (res) => {
      windowHeight.value = res.windowHeight
      pageHeight.value = res.windowHeight
      console.log('私聊页面窗口高度:', res.windowHeight)
    }
  })

  // 监听键盘高度变化
  // #ifdef APP-PLUS
  uni.onKeyboardHeightChange((res) => {
    console.log('私聊页面键盘高度变化:', res.height)
    keyboardHeight.value = res.height
  })
  // #endif
  
  // #ifdef MP-WEIXIN
  // 小程序平台监听键盘高度变化
  if (uni.onKeyboardHeightChange) {
    uni.onKeyboardHeightChange((res) => {
      console.log('私聊页面小程序键盘高度变化:', res.height)
      keyboardHeight.value = res.height
    })
  }
  // #endif
})

onUnmounted(() => {
  // 移除键盘监听
  uni.offKeyboardHeightChange()
})

onUnload(() => {
  stopPolling()
})

// 方法定义
const resolveAvatarString = (value) => {
  if (!value) return ''
  if (typeof value === 'string') {
    return value.trim()
  }
  return value
}

const getOtherAvatarUrl = (message) => {
  const avatar = resolveAvatarString(
    otherUserInfo.value?.avatar_url ||
    message?.sender?.avatar_url ||
    message?.sender?.avatar
  )
  return avatar || defaultAvatarDataUrl
}

const hasOtherAvatar = (message) => {
  return !!resolveAvatarString(
    otherUserInfo.value?.avatar_url ||
    message?.sender?.avatar_url ||
    message?.sender?.avatar
  )
}

const getOtherAvatarInitial = (message) => {
  return otherUserInfo.value?.nickname?.charAt(0) ||
    message?.sender?.nickname?.charAt(0) ||
    '用'
}

const updateOtherUserProfile = (info = {}) => {
  if (!info) return

  const normalizedInfo = {
    id: info.id || otherUserId.value,
    nickname: info.nickname || otherUserNickname.value,
    avatar_url: info.avatar_url || info.avatar || null
  }

  if (!otherUserInfo.value) {
    otherUserInfo.value = normalizedInfo
    if (normalizedInfo.nickname) {
      otherUserNickname.value = normalizedInfo.nickname
    }
    return
  }

  const shouldUpdateAvatar = normalizedInfo.avatar_url && normalizedInfo.avatar_url !== otherUserInfo.value.avatar_url
  const shouldUpdateNickname = normalizedInfo.nickname && normalizedInfo.nickname !== otherUserInfo.value.nickname

  if (shouldUpdateAvatar || shouldUpdateNickname) {
    otherUserInfo.value = {
      ...otherUserInfo.value,
      avatar_url: shouldUpdateAvatar ? normalizedInfo.avatar_url : otherUserInfo.value.avatar_url,
      nickname: shouldUpdateNickname ? normalizedInfo.nickname : otherUserInfo.value.nickname
    }
  }

  if (shouldUpdateNickname) {
    otherUserNickname.value = normalizedInfo.nickname
  }
}

const syncOtherUserInfoFromMessages = (messageList = []) => {
  if (!Array.isArray(messageList) || messageList.length === 0) {
    return
  }

  const otherMessage = messageList.find(msg => msg.sender_id?.toString() !== currentUser.value?.id?.toString())
  if (otherMessage && otherMessage.sender) {
    updateOtherUserProfile({
      id: otherMessage.sender.id,
      nickname: otherMessage.sender.nickname,
      avatar_url: otherMessage.sender.avatar_url || otherMessage.sender.avatar
    })
  }
}

const loadOtherUserInfo = async () => {
  if (!otherUserId.value) return
  try {
    const response = await userAPI.getUserById(otherUserId.value)
    if (response.success && response.data) {
      updateOtherUserProfile({
        id: response.data.id,
        nickname: response.data.nickname,
        avatar_url: response.data.avatar_url
      })
    }
  } catch (error) {
    console.error('获取对方用户信息失败:', error)
  }
}

const loadMessages = async (isRefresh = false) => {
  if (isLoading.value && !isRefresh) return

  try {
    if (isRefresh) {
      isLoadingMore.value = true
    } else {
      isLoading.value = true
    }

    const response = await chatAPI.getPrivateChatMessages(
      otherUserId.value,
      pagination.value.page,
      pagination.value.pageSize
    )

    if (response.success) {
      const newMessages = response.data?.data || []

      if (isRefresh) {
        // 加载更多（历史消息）
        messages.value = [...newMessages.reverse(), ...messages.value]
        pagination.value.page++
      } else {
        // 首次加载
        messages.value = newMessages.reverse()
        scrollToBottom()
      }

      // 提取对方用户信息(从消息中获取)
      syncOtherUserInfoFromMessages(newMessages)

      // 如果还是没有找到对方信息(消息为空或都是自己发的),使用URL参数初始化
      if (!otherUserInfo.value && !isRefresh) {
        updateOtherUserProfile({
          id: otherUserId.value,
          nickname: otherUserNickname.value,
          avatar_url: null
        })
      }

      hasMore.value = response.data?.pagination?.page < response.data?.pagination?.totalPages
    }

  } catch (error) {
    console.error('加载消息失败:', error)
    utils.handleError(error, '加载消息失败')
  } finally {
    isLoading.value = false
    isLoadingMore.value = false
  }
}

const loadMoreMessages = () => {
  if (!hasMore.value || isLoadingMore.value) return
  loadMessages(true)
}

const sendMessage = async () => {
  const content = inputMessage.value.trim()
  if (!content || isSending.value) return

  // 检查聊天额度
  const hasCredit = await CreditChecker.checkChatCredit(1, {
    fromPage: `/pages/chat/private?userId=${otherUserId.value}&nickname=${encodeURIComponent(otherUserNickname.value)}`
  })
  
  if (!hasCredit) {
    return
  }

  const shouldConsumeCredits = await CreditChecker.shouldConsumeChatCredits()

  try {
    isSending.value = true

    const response = await chatAPI.sendPrivateMessage(otherUserId.value, content)

    if (response.success) {
      if (shouldConsumeCredits) {
        CreditChecker.reduceLocalCredit(CreditChecker.CREDIT_TYPES.CHAT, 1)
      } else {
        incrementFreeUsageCounter(1)
      }
      
      // 添加到消息列表
      messages.value.push(response.data)
      inputMessage.value = ''
      scrollToBottom()
    } else {
      uni.showToast({
        title: response.message || '发送失败',
        icon: 'none'
      })
    }

  } catch (error) {
    console.error('发送消息失败:', error)

    const quotaData = getChatQuotaDataFromError(error)

    // 如果是禁言错误，显示禁言提示
    if (error.message && error.message.includes('禁言')) {
      uni.showModal({
        title: '发言受限',
        content: '您已被管理员禁言，无法发送消息。如有疑问，请联系管理员。',
        showCancel: false,
        confirmText: '知道了'
      })
    } else if (quotaData && quotaData.mode === 'free') {
      showFreeChatQuotaModal(quotaData)
    } else if (error.message && error.message.includes('额度不足')) {
      // 如果是额度不足错误，再次检查并处理
      await CreditChecker.checkChatCredit(1, {
        fromPage: `/pages/chat/private?userId=${otherUserId.value}&nickname=${encodeURIComponent(otherUserNickname.value)}`
      })
    } else {
      uni.showToast({
        title: '发送失败',
        icon: 'none'
      })
    }
  } finally {
    isSending.value = false
  }
}



/**
 * 格式化时间 - 显示为**年**月*日 时:分:秒格式
 */
const formatTime = (timeStr) => {
  const time = new Date(timeStr)
  const year = time.getFullYear()
  const month = time.getMonth() + 1
  const day = time.getDate()
  const hours = time.getHours().toString().padStart(2, '0')
  const minutes = time.getMinutes().toString().padStart(2, '0')
  const seconds = time.getSeconds().toString().padStart(2, '0')

  return `${year}年${month}月${day}日 ${hours}:${minutes}:${seconds}`
}

const scrollToBottom = () => {
  nextTick(() => {
    scrollTop.value = 999999
  })
}

const startPolling = () => {
  pollingTimer = setInterval(async () => {
    try {
      const lastMessage = messages.value[messages.value.length - 1]
      const lastMessageId = lastMessage ? lastMessage.id : 0

      const response = await chatAPI.getPrivateNewMessages(otherUserId.value, lastMessageId)

      if (response.success && response.data.length > 0) {
        messages.value.push(...response.data)
        scrollToBottom()
        syncOtherUserInfoFromMessages(response.data)
      }
    } catch (error) {
      console.error('轮询新消息失败:', error)
    }
  }, pollingInterval)
}

const stopPolling = () => {
  if (pollingTimer) {
    clearInterval(pollingTimer)
    pollingTimer = null
  }
}

const goBack = () => {
  uni.navigateBack()
}

// 联系方式查看相关方法
const showContactInfo = async () => {
  try {
    // 先检查查看联系方式额度
    const hasCredit = await CreditChecker.checkContactViewCredit({
      fromPage: `/pages/chat/private?userId=${otherUserId.value}`
    })
    if (!hasCredit) {
      return
    }

    showContactModal.value = true
    contactInfo.loading = true
    contactInfo.error = null
    contactInfo.data = null

    // 检查查看权限
    const permissionResponse = await contactViewAPI.checkViewPermission(otherUserId.value)

    if (permissionResponse.success) {
      contactPermission.value = permissionResponse.data
      contactInfo.loading = false
    } else {
      contactInfo.error = permissionResponse.message || '检查权限失败'
      contactInfo.loading = false
    }
  } catch (error) {
    console.error('检查联系方式查看权限失败:', error)
    contactInfo.error = '检查权限失败，请重试'
    contactInfo.loading = false
  }
}

const confirmViewContact = async () => {
  try {
    contactInfo.loading = true
    contactInfo.error = null

    const response = await contactViewAPI.getUserContact(otherUserId.value)

    if (response.success) {
      contactInfo.data = response.data
      contactInfo.loading = false

      // 如果使用了额度（不是免费查看），则减少本地额度
      if (response.data.used_credits) {
        CreditChecker.reduceLocalCredit('contact_view', 1)
      }
    } else {
      contactInfo.error = response.message || '获取联系方式失败'
      contactInfo.loading = false
    }
  } catch (error) {
    console.error('获取联系方式失败:', error)
    contactInfo.error = '获取联系方式失败，请重试'
    contactInfo.loading = false
  }
}

const getContactInfo = () => {
  confirmViewContact()
}

const closeContactModal = () => {
  showContactModal.value = false
  contactInfo.loading = false
  contactInfo.error = null
  contactInfo.data = null
  contactPermission.value = {}
}

// 复制文本到剪贴板
const copyText = (text) => {
  uni.setClipboardData({
    data: text,
    success: () => {
      uni.showToast({
        title: '已复制到剪贴板',
        icon: 'success',
        duration: 2000
      })
    },
    fail: () => {
      uni.showToast({
        title: '复制失败',
        icon: 'none',
        duration: 2000
      })
    }
  })
}

// 拨打电话
const makePhoneCall = (phoneNumber) => {
  uni.makePhoneCall({
    phoneNumber: phoneNumber,
    success: () => {
      console.log('拨打电话成功')
    },
    fail: (error) => {
      console.error('拨打电话失败:', error)
      uni.showToast({
        title: '拨打失败',
        icon: 'none',
        duration: 2000
      })
    }
  })
}

// 头像长按提示
const showAvatarTip = () => {
  uni.showToast({
    title: '点击查看联系方式',
    icon: 'none',
    duration: 1500
  })
}

// 获取查看按钮文字
const getViewButtonText = () => {
  if (!contactPermission.value) {
    return '查看联系方式'
  }

  // 优先显示免费次数
  if (contactPermission.value.remaining_free_views > 0) {
    return `剩余${contactPermission.value.remaining_free_views}次`
  }

  // 如果免费次数用完了，但有购买的次数
  if (contactPermission.value.remaining_credits > 0) {
    return `剩余${contactPermission.value.remaining_credits}次`
  }

  // 如果是真的免费（比如系统未开启收费功能）
  if (contactPermission.value.is_free && contactPermission.value.cost === 0) {
    return '免费查看'
  }

  // 需要付费
  return `支付 ¥${contactPermission.value.cost} 查看`
}
</script>

<style scoped>
.private-chat-container {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background: #ededed;
  overflow: hidden;
}

/* 删除了自定义导航栏样式 */

/* 消息列表 */
.message-list {
  flex: 1;
  padding: 20rpx 30rpx;
  padding-bottom: 140rpx;
  background: #ededed;
}

.message-item {
  margin-bottom: 30rpx;
}





.message-content {
  display: flex;
  flex-direction: column;
  align-items: flex-start; /* 左对齐，让气泡宽度自适应 */
  max-width: calc(100vw - 200rpx); /* 留出头像和边距的空间 */
}

/* 右侧消息的内容容器需要右对齐 */
.right-message .message-content {
  align-items: flex-end;
}

.message-bubble {
  padding: 20rpx 30rpx;
  border-radius: 16rpx;
  word-wrap: break-word;
  max-width: 500rpx; /* 气泡本身的最大宽度限制 */
  width: fit-content; /* 宽度自适应内容 */
  position: relative;
}

.message-time {
  font-size: 24rpx;
  color: #999;
  margin-top: 8rpx;
}

.loading-more {
  text-align: center;
  padding: 20rpx;
  color: #666;
  font-size: 24rpx;
}

.empty-state {
  text-align: center;
  padding: 100rpx 20rpx;
}

.empty-text {
  color: #999;
  font-size: 28rpx;
}

.input-section {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background: white;
  border-top: 1rpx solid #e0e0e0;
  z-index: 100;
  transition: bottom 0.3s ease;
  box-sizing: border-box;
}

.input-container {
  display: flex;
  align-items: center;
  gap: 20rpx;
  padding: 20rpx 30rpx;
}

.contact-btn-left {
  width: 80rpx;
  height: 80rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 50%;
  background: rgba(0, 122, 255, 0.1);
  flex-shrink: 0;
}

.contact-icon {
  font-size: 36rpx;
}

.message-input {
  flex: 1;
  background: #f5f5f5;
  border: 1rpx solid #e0e0e0;
  border-radius: 25rpx;
  padding: 20rpx 30rpx;
  font-size: 28rpx;
}

.send-btn {
  background: #007aff;
  color: white;
  border: none;
  border-radius: 25rpx;
  padding: 20rpx 30rpx;
  font-size: 28rpx;
  min-width: 120rpx;
}

.send-btn:disabled {
  background: #ccc;
  color: #999;
}

/* 新的微信风格样式 */
.message-wrapper {
  display: flex;
  align-items: flex-start;
  gap: 20rpx;
}

.left-message {
  justify-content: flex-start;
}

.right-message {
  justify-content: flex-end;
}

	/* 右侧（自己）消息的头像与屏幕右侧留出安全间距，避免被滚动条或边缘裁切 */
	.right-message .avatar-container {
	  margin-right: 30rpx;
	}


.avatar-container {
  flex-shrink: 0;
  width: 80rpx;
  height: 80rpx;
  position: relative;
}

/* 可点击头像样式 */
.clickable-avatar {
  cursor: pointer;
}

.clickable-avatar:active {
  opacity: 0.8;
  transform: scale(0.95);
  transition: all 0.1s ease;
}

/* 联系方式提示图标 */
.contact-hint {
  position: absolute;
  bottom: -2rpx;
  right: -2rpx;
  width: 24rpx;
  height: 24rpx;
  background: #007aff;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  border: 2rpx solid white;
}

.hint-icon {
  font-size: 16rpx;
  color: white;
}

.user-avatar {
  width: 80rpx;
  height: 80rpx;
  border-radius: 8rpx;
  background: #f5f5f5;
}

.placeholder-avatar {
  filter: grayscale(0.5);
}

.avatar-placeholder-text {
  position: absolute;
  top: 0;
  left: 0;
  width: 80rpx;
  height: 80rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 28rpx;
  color: #666;
  pointer-events: none;
}

.avatar-placeholder {
  width: 80rpx;
  height: 80rpx;
  border-radius: 8rpx;
  background: #ddd;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 28rpx;
  color: #666;
}

.left-bubble {
  background: #ffffff;
  border: 1rpx solid #e5e5e5;
  border-radius: 16rpx 16rpx 16rpx 4rpx;
}

.right-bubble {
  background: #95ec69;
  color: #000;
  border-radius: 16rpx 16rpx 4rpx 16rpx;
}

.message-text {
  font-size: 32rpx;
  line-height: 1.4;
  word-break: break-all;
}

/* 联系方式弹窗样式 */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 2000;
}

.contact-modal {
  background: white;
  border-radius: 20rpx;
  width: 600rpx;
  max-height: 80vh;
  overflow: hidden;
}

.modal-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 40rpx 40rpx 20rpx;
  border-bottom: 1rpx solid #eee;
}

.modal-title {
  font-size: 36rpx;
  font-weight: bold;
  color: #333;
}

.modal-close {
  font-size: 48rpx;
  color: #999;
  width: 60rpx;
  height: 60rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.modal-content {
  padding: 40rpx;
}

.loading-state,
.error-state {
  text-align: center;
  padding: 60rpx 20rpx;
}

.error-text {
  color: #ff4444;
  margin-bottom: 30rpx;
}

.retry-btn {
  background: #007aff;
  color: white;
  border: none;
  border-radius: 8rpx;
  padding: 20rpx 40rpx;
  font-size: 28rpx;
}

.contact-info {
  text-align: center;
}

.user-info {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-bottom: 40rpx;
}

.contact-avatar-wrapper {
  position: relative;
  width: 120rpx;
  height: 120rpx;
  margin-bottom: 20rpx;
}

.contact-avatar {
  width: 120rpx;
  height: 120rpx;
  border-radius: 12rpx;
  background: #f5f5f5;
}

.contact-avatar-overlay {
  position: absolute;
  top: 0;
  left: 0;
  width: 120rpx;
  height: 120rpx;
  border-radius: 12rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 48rpx;
  color: #666;
  pointer-events: none;
}

.contact-name {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

.contact-details {
  text-align: left;
}

.contact-item {
  margin-bottom: 30rpx;
  padding: 20rpx;
  background: #f8f9fa;
  border-radius: 12rpx;
}

.contact-label {
  font-size: 28rpx;
  color: #666;
  margin-bottom: 10rpx;
  display: block;
}

.contact-value {
  font-size: 32rpx;
  color: #333;
  font-weight: bold;
  margin-bottom: 15rpx;
  display: block;
  word-break: break-all;
}

.contact-actions {
  display: flex;
  gap: 10rpx;
}

.action-btn {
  padding: 8rpx 16rpx;
  border-radius: 8rpx;
  font-size: 24rpx;
  border: none;
  color: white;
  min-width: 80rpx;
  height: 60rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.copy-btn {
  background: #409EFF;
}

.copy-btn:active {
  background: #337ecc;
}

.call-btn {
  background: #67C23A;
}

.call-btn:active {
  background: #529b2e;
}

.no-contact-info {
  text-align: center;
  padding: 40rpx 20rpx;
  background: #f8f9fa;
  border-radius: 12rpx;
  margin-bottom: 20rpx;
}

.no-contact-text {
  font-size: 28rpx;
  color: #999;
}

.fee-info,
.remaining-info {
  text-align: center;
  margin-top: 30rpx;
}

.fee-text {
  color: #ff6600;
  font-size: 28rpx;
}

.remaining-text {
  color: #666;
  font-size: 26rpx;
}

.permission-check {
  text-align: center;
}

.check-info {
  margin-bottom: 40rpx;
}

.check-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 20rpx;
}

.check-message {
  font-size: 28rpx;
  color: #666;
}

.check-fee {
  font-size: 28rpx;
  color: #ff6600;
}

.check-actions {
  display: flex;
  gap: 30rpx;
  justify-content: center;
}

.cancel-btn {
  background: #f5f5f5;
  color: #666;
  border: none;
  border-radius: 8rpx;
  padding: 24rpx 40rpx;
  font-size: 28rpx;
}

.confirm-btn {
  background: #007aff;
  color: white;
  border: none;
  border-radius: 8rpx;
  padding: 24rpx 40rpx;
  font-size: 28rpx;
}
</style>
